/**
 * Created by pankajmishra on 16/01/15.
 */
define(['jquery','mustache','module/common/richbox'], function($, Mustache, richbox){
    return function(item){

        item['commentCount'] = function(){
            return this.comments?this.comments.length:0;
        }
        var template = require('module/template/homeTemplate');
        var itemDom = $(Mustache.to_html(template['info-item'], item));


        var editClick = function(){
            var div = $(template['home-update-rich-text']);
            itemDom.find('.panel-collapse').empty();
            itemDom.find('.panel-collapse').append(div);
            div.html(item.update_txt);
            var error = $('<div class="error"> <p class="alert-danger" > Please write what you want to update first in text area, then try ' +
            'to submit </p> </div>');
            div.summernote({
                focus :true,
                hideToolBar : true,
                toolbar: richbox.sm_option
            });
            itemDom.find('.panel-collapse').append($(template['home-update-sc']));

            itemDom.find('a.js_showfont').once('click', function(){
                div.showToolBar();
            });

            itemDom.find('button.cancel').once('click', function(){
                itemDom.empty();
                itemDom.html($(Mustache.to_html(template['info-item'], item)).html());
                itemDom.find('.js_edit_info').once('click', editClick);
            });


            itemDom.find('button.submit').once('click', function(){
                var txt = div.code();
                var testCode = txt.replace(/&nbsp;/g,'');
                testCode = testCode.replace(/<p>/g,'');
                testCode = testCode.replace(/<\/p>/g,'');
                testCode = testCode.replace(/<br>/g,'');
                if(testCode.trim().length == 0){
                    itemDom.prepend(error);
                    return;
                }
                itemDom.empty();
                var ajaxObj =  {
                    url : '/user/saveUpdate',
                    type : "POST",
                    data : {
                        update : txt,
                        id :  item.upid
                    },
                    dataType: "json"
                };
                var loader = template.small_loader;
                itemDom.append(loader);
                $.ajax(ajaxObj).done(function(data) {
                    itemDom.empty();
                    item.update_txt = data.update_txt;
                    itemDom.html($(Mustache.to_html(template['info-item'], item)).html());
                    itemDom.find('.js_edit_info').once('click', editClick);
                    // update module factory
                }).fail(function() {
                    itemDom.empty();
                    alert('oops ..');
                });


            });
        };


        itemDom.find('.js_edit_info').once('click', editClick);
        return itemDom;
    };
});